import {Blog} from"../model/Blog.js"
import { Op } from "sequelize"

const fn_list =async(ctx,next)=>{
    let keyword =ctx.request.query.keyword || ''
    console.log(keyword);
    let where
    if (keyword) {
        where={
            [Op.or]:[
                {
                    title:{
                        [Op.like]:`%${keyword}%`
                    },
                },
                {
                    author:{
                        [Op.like]:`%${keyword}%`
                    }
                },
            ]
        }
    }
    let blogs =await Blog.findAll(
        {where}
    )
    ctx.body={
        code:1000,
        msg:'列表成功',
        data:blogs
    }
    
 
    ctx.body='列表'
}
const fn_getById=async(ctx,next)=>{

    ctx.body="指定博客"

    let id =ctx.params.id || 0;
    let blog =await Blog.findByPk(id);
    ctx.body={
        code:1000,
        msg:'成功',
        data:blog

    }
}
const fn_add=async(ctx ,next)=>{
    ctx.body ="新增"

    let obj =ctx.request.body;

    if(obj && obj.title &&obj.author &&obj.title.length >0 && obj.title.length<80 &&obj.author.length>5 && obj.author.length<=30){
        
    }
}
const fn_edit = async (ctx, next) => {
    // ctx.body = '修改'
    /*
    1. 获取前端传过来的数据
    2. 处理相关业务逻辑
    3. 返回处理过后的响应结果
*/
    let id = ctx.params.id || 0;
    let obj = ctx.request.body;
    await Blog.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: '修改成功',
        data: null
    }
}

const fn_del = async (ctx, next) => {
    ctx.body = '删除'
    /*
        1. 获取前端传过来的数据
        2. 处理相关业务逻辑
        3. 返回处理过后的响应结果
    */

    // 拿到id
    let id = ctx.params.id || 0;

    // 处理业务逻辑：删除数据库中对应id的记录
    let count = await Blog.destroy({
        where: {
            id: id
        }
    })
    // 处理响应数据
    let res;
    if (count === 1) {
        res = {
            code: 1000,
            msg: '删除成功',
            data: null
        }
    } else {
        res = {
            code: 4000,
            msg: '删除失败',
            data: null
        }
    }

    ctx.body = res;

}

//导出路由结构
export default[
    {
        method:'get',
        url:'/blogs',
        fn:fn_list
    },
    {
        method:"get",
        url:'/blogs/:id',
        fn:fn_getById
    },
    {
        method:'post',
        url:'/blogs',
        fn:fn_add
    },
    {
        method:'put',
        url:'/blogs/:id',
        fn:fn_edit
    },
    {
        method:'del',
        url:'/blogs/:id',
        fn:fn_del
    },
]